import datetime
import traceback
import urllib

from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR

from programApi.exam.exam_models import ExamContent, ExamScore, ExamHistory
from programApi.exam.exam_serializers import ExamHistorySerializer, ExamNameSerializer, ExamScoreSerializer

"""
    @url('/exam/')
"""


class ExamViewSet(viewsets.ViewSet):

    def list(self, request):
        """
        exam_viewset 的 get method
        @param request:
        ?type=exam =>
            &name = null => 查询考试名称
            &name != null => 查询examName=name的题目内容
        @return:
        """
        try:
            params = self.request.query_params
            todo = params.get('type')
            if todo == 'exam':
                # 如果有传入试卷名称，获取试卷的题目内容
                if params.get('name'):
                    name = params.get('name')
                    queryset = ExamContent.objects.filter(examName=name)
                    exam_list = []
                    answer_list = []
                    num = 1
                    # 重新封装返回对象
                    for i in queryset:
                        dict = {'options': [{'id': 'A', 'name': i.optionA}, {'id': 'B', 'name': i.optionB},
                                            {'id': 'C', 'name': i.optionC},
                                            {'id': 'D', 'name': i.optionD}, ]}
                        exam_list.append(
                            {'examContent': i.examContent, 'options': dict, 'answer': i.examAnswer})
                        answer_list.append(
                            {'num': num, 'examContent': i.examContent, 'option': ' ', 'answer': i.examAnswer,
                             'userAnswer': ' ', 'display': None})
                        num += 1
                    result = {'size': len(queryset), 'examList': exam_list, 'answerSheet': answer_list}
                    return Response(data=result)
                # 获取全部考试（试卷）
                else:
                    queryset = ExamContent.objects.values("examName").distinct()
                    serializer = ExamNameSerializer(queryset, many=True)
                    return Response(serializer.data)
            # 获取历史数据
            elif todo == 'history':
                user_id = params.get('openid')
                # 如果有传入试卷名称和时间，返回该试卷的答题记录
                if params.get('name') and params.get('time'):
                    # 处理转码以及时间格式
                    name = urllib.parse.unquote(params.get('name'))
                    time = urllib.parse.unquote(params.get('time'))
                    time = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
                    queryset = ExamHistory.objects.filter(userId=user_id, examName=name, addTime=time)
                    serializer = ExamHistorySerializer(queryset, many=True)
                    print(serializer.data)
                    return Response(serializer.data)
                # 如果没有传入，返回用户所有提交过的试卷历史记录
                else:
                    score_query_set = ExamScore.objects.filter(userId=user_id)
                    exam_history_score_list = []
                    for i in score_query_set:
                        exam_history_score_list.append(
                            {'addTime': str(
                                datetime.datetime.strptime(str(i.addTime).split('+')[0], "%Y-%m-%d %H:%M:%S")),
                                'examName': i.examName, 'examScore': i.examScore})
                    result = {'examList': exam_history_score_list}
                    return Response(data=result)
        except Exception as e:
            traceback.print_exc()
        return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)

    def create(self, request):
        """
        exam_view_set 的 post method，处理提交考试记录
        @param request:
        answerSheet : 答题卡 -> [{userId,examName,examContent,userChosen,examAnswer}]
        userId : 用户Id
        examName : 试卷名称
        @return:
        """
        # request param
        data = request.data.get('answerSheet')  # 答题卡数据
        user_id = request.data.get('userId')  # openId
        exam_name = request.data.get('examName')  # 试卷名称
        # 处理数据需要的临时变量
        total = len(data)  # 总题数
        correct_nums = 0  # 正确题数
        score = 0  # 分数
        now = datetime.datetime.now()  # 获取时间
        now = now.strptime(str(now).split('.')[0], '%Y-%m-%d %H:%M:%S')  # 处理时间格式，仅保存年月日时分秒
        success = True  # 是否成功
        # 遍历答题卡，向数据库考试历史表插入数据
        for i in data:
            user_answer = "未选择"
            exam_answer = i.get('answer')
            # 如果用户有选择选项
            if i.get('userAnswer') != ' ':
                user_answer = i.get('userAnswer')
            history_serializer = ExamHistorySerializer(data={'userId': user_id,
                                                             'examName': exam_name,
                                                             'examContent': i.get('examContent'),
                                                             'userChosen': user_answer,
                                                             'examAnswer': exam_answer,
                                                             'addTime': now})
            # 判断是否正确
            if user_answer == exam_answer:
                correct_nums += 1
            if history_serializer.is_valid():
                history_serializer.save()
            else:
                success = False
        # 计算分数并保存到数据库考试得分表中
        score = round(correct_nums / total, 2) * 100
        score_serializer = ExamScoreSerializer(
            data={'userId': user_id, 'examName': exam_name, 'examScore': score, 'addTime': now.isoformat()})
        if score_serializer.is_valid():
            score_serializer.save()
        else:
            success = False
        # 如果未修改flag
        if success:
            data = {'code': 200, 'score': score}
            return Response(data)
        else:
            return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
